#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;

using System.Web;

using System.Collections;
using WaveMaster.Holidays.Club.Domain;
using WaveMaster.Holidays.Club.Service;

#endregion

namespace WaveMaster.Holidays.Club.Web
{
    public partial class ConfirmBookingForm : Form, IPassengerParentForm
    {
        CheckIn m_booking;
        SeaPortService m_SeaPortService;
        CheckInService m_bookingService;
        PassportService m_passportService;
        User m_current_user;
        EditMode m_editmode;
        CheckInService m_userService;
        MainForm m_mainForm;
        TripService m_tripService;
        TravelAgentService m_TravelAgentService;
        UserControlManageConfirmBooking m_parentForm;

        public ConfirmBookingForm(string name, CheckIn user, User currentUser, MainForm mainForm, UserControlManageConfirmBooking parentForm, EditMode editmode)
        {
            InitializeComponent();
            
            m_current_user = currentUser;
            m_mainForm = mainForm;
            this.Name = name;
            m_parentForm = parentForm;
            m_SeaPortService = (SeaPortService)ServiceFactory.Instance().GetService(ServiceFactory.SEAPORT_SERVICE);
            m_tripService = (TripService)ServiceFactory.Instance().GetService(ServiceFactory.TRIP_SERVICE);
            m_userService = (CheckInService)ServiceFactory.Instance().GetService(ServiceFactory.BOOKING_SERVICE);
            m_bookingService = (CheckInService)ServiceFactory.Instance().GetService(ServiceFactory.BOOKING_SERVICE);
            m_TravelAgentService = (TravelAgentService)ServiceFactory.Instance().GetService(ServiceFactory.TRAVEL_AGENT_SERVICE);
            m_passportService = (PassportService)ServiceFactory.Instance().GetService(ServiceFactory.PASSPORT_SERVICE);
            initButtonEvent();
            initComboDataSource();
            if (user.m_bookingID == 0)
            {
               
            }
            else
            {
                m_booking = user;
                loadBooking(); 
                //enableForm(editmode == EditMode.Edit);
                enableForm(false);
            }
            setEditMode(editmode);
            //enableForm(false);
           
        }

        private void initButtonEvent()
        {
            //toolBarButtonClear.Click += new EventHandler(toolBarButtonClear_Click);
            toolBarButtonSave.Click += new EventHandler(toolBarButtonSave_Click);
            //toolBarButtonDelete.Click += new EventHandler(toolBarButtonDelete_Click);
            toolBarButtonRefresh.Click += new EventHandler(toolBarButtonRefresh_Click);
            //toolBarButtonEdit.Click += new EventHandler(toolBarButtonEdit_Click);
            //toolBarButtonSearch.Click += new EventHandler(toolBarButtonSearch_Click);
            toolBarButtonCancel.Click += new EventHandler(toolBarButtonCancel_Click);
        }
              
        void toolBarButtonEdit_Click(object sender, EventArgs e)
        {
            setEditMode(EditMode.Edit);
           // enableForm(!toolBarButtonEdit.Enabled);
        }

        void toolBarButtonCancel_Click(object sender, EventArgs e)
        {
            if (m_editmode == EditMode.Load)
                this.Close();
            else
            MessageBox.Show("Are you sure to cancel?", "Confirmation", MessageBoxButtons.YesNo,
               MessageBoxIcon.Question, new EventHandler(cancelConfirmation));
        }

        void cancelConfirmation(object sender, EventArgs e)
        {
             MessageBoxWindow msg = (MessageBoxWindow)sender;
             if (msg.DialogResult == DialogResult.Yes)
             {
                 this.Close();
             }
        }
        private void initComboDataSource()
        {

        }

        void toolBarButtonRefresh_Click(object sender, EventArgs e)
        {
            //loadAllUser();
            initComboDataSource();
            if (m_editmode == EditMode.Load || m_editmode == EditMode.Edit)
                loadBooking();
        }

        private void clearErrorProvider()
        {
            //errorProviderUser.SetError(textBoxUserCode, "");
            //errorProviderUser.SetError(textBoxName, "");
            //errorProviderUser.SetError(numericUpDownBooked, "");

        }
        private bool isValidForm()
        {
           // clearErrorProvider();
           //// bool valid_a = textBoxUserCode.Text != string.Empty;
           // decimal available = 0;
           // TicketType tt = (TicketType)Enum.Parse(typeof(TicketType), comboBoxTicketType.Text);
           // available = m_bookingService.GetAvailableBook(m_current_user.TravelAgent.TravelAgentID, tt);

           // bool valid_b = textBoxName.Text != string.Empty;
           // bool valid_c = numericUpDownBooked.Value != 0;
           // bool valid_d = comboBoxSeaPort.SelectedValue != null;
           // bool valid_e = comboBoxTrip.SelectedValue != null;
           // bool valid_g = comboBoxTravelAgent.SelectedValue != null;
           // bool valid_f = listViewPassenger.Items.Count <= available;
           //// if (!valid_a) errorProviderUser.SetError(textBoxUserCode, "Code can not be empty");
           // if (!valid_b) errorProviderUser.SetError(textBoxName, "Group can not be empty");
           // if (!valid_c) errorProviderUser.SetError(numericUpDownBooked, "Book number can not be empty");
           // if (!valid_d) errorProviderUser.SetError(comboBoxSeaPort, "SeaPort not be empty");
           // if (!valid_e) errorProviderUser.SetError(comboBoxTrip, "Trip can not be empty");
           // if (!valid_f) errorProviderUser.SetError(numericUpDownBooked, "Book stock exceed available stock");
           // if (!valid_g) errorProviderUser.SetError(comboBoxTravelAgent, "Travel agent cannot empty");
           // //return valid_b && valid_c && valid_d && valid_e && valid_f && valid_g;

            return true;
        }

        void toolBarButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (isValidForm())
                {
                    bool bookConfirm = true;
                    foreach (ListViewItem itm in listViewPassenger.Items)
                    {
                        Passenger pass = (Passenger)itm.Tag;
                        if (pass == null) continue;
                        if (itm.Checked)
                        {
                            m_bookingService.UpdatePassangerStatus(pass, PassengerStatus.Boarding);
                        }
                        else
                        {
                            m_bookingService.UpdatePassangerStatus(pass, PassengerStatus.CheckIn);
                            bookConfirm = false;
                        }
                    }
                    if (bookConfirm)
                        m_bookingService.UpdateCheckInStatus(m_booking, CheckInStatus.Boarding);
                    else
                        m_bookingService.UpdateCheckInStatus(m_booking, CheckInStatus.CheckIn);

                    m_parentForm.LoadAllBooking();
                  //  MessageBox.Show("Record has been saved.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    MessageBox.Show("Record has been saved [" + m_booking.m_bookingCode + "]", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, new EventHandler(closeForm));
                    //clearForm();
                    //loadAllUser();
                    //setEditMode(EditMode.Saved);
                   // this.Close();
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error Exception", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

        }
        void closeForm(object sender, EventArgs e)
        {
            this.Close();
        }

        private void setEditMode(EditMode editMode)
        {
            toolBarButtonSave.Enabled = (editMode == EditMode.Create || editMode == EditMode.Edit || editMode == EditMode.Saved || editMode == EditMode.Delete) && m_current_user.RoleDetails(this.Name).NewFlag && m_booking.m_bookingStatus != CheckInStatus.Closed;
            m_editmode = editMode;
            labelEditMode.Text = "[" + editMode + "]";
        }

        private void enableForm(bool enable)
        {
            buttonDatils.Enabled = listViewPassenger.SelectedItem != null;
            textBoxName.ReadOnly = !enable;
            //textBoxUserCode.ReadOnly = !enable;
            numericUpDownBooked.Enabled = enable;
            textBoxSeaPort.ReadOnly= !enable;
            dateTimePickerDate.Enabled = enable;
            textBoxTrip.ReadOnly= !enable;
            //listViewPassenger.Enabled = enable;
            textBoxRemark.ReadOnly = !enable;
           // buttonREmove.Enabled = enable && listViewPassenger.SelectedItem != null;
           // buttonAddPassenger.Enabled = enable;
            textBoxticketType.ReadOnly = !enable;
            dateTimePickerBookDate.Enabled = enable;
            textBoxTravelAgent.ReadOnly = !enable;// && (m_current_user.UserType == UserType.Administrators);
            dateTimePickerReturn.Enabled = enable;
            dateTimePickerReturnTime.Enabled = enable;
            dateTimePickerDepTime.Enabled = enable;
        }


        private void loadBooking()
        {
            m_booking.m_trip = m_tripService.GetTripByID(m_booking.m_trip.m_tripID);
            m_booking.m_trip.m_seaPort = m_SeaPortService.GetSeaPortByID(m_booking.m_trip.m_seaPort.m_seaPortID);
            m_booking.m_travelAgent = m_TravelAgentService.GetTravelAgentByID(m_booking.m_travelAgent.TravelAgentID);

            if (m_booking.m_bookingStatus == CheckInStatus.ReCeckIn)
            {
                m_booking.BookingHistory = m_bookingService.GetCheckInHistoryByBookingID(m_booking.m_bookingID);
                if (m_booking.BookingHistory != null)
                {
                    m_booking.BookingHistory.m_trip = m_tripService.GetTripByID(m_booking.BookingHistory.m_trip.m_tripID);
                    m_booking.BookingHistory.m_trip.m_seaPort = m_SeaPortService.GetSeaPortByID(m_booking.BookingHistory.m_trip.m_seaPort.m_seaPortID);
                    m_booking.BookingHistory.m_travelAgent = m_TravelAgentService.GetTravelAgentByID(m_booking.BookingHistory.m_travelAgent.TravelAgentID);

                    textBoxName.BackColor = m_booking.m_groupName == m_booking.BookingHistory.m_groupName ? Color.Cornsilk : Color.Red;
                    textBoxUserCode.BackColor = m_booking.m_bookingCode == m_booking.BookingHistory.m_bookingCode ? Color.Cornsilk : Color.Red;
                    numericUpDownBooked.BackColor = m_booking.m_bookNumber == m_booking.BookingHistory.m_bookNumber ? Color.Cornsilk : Color.Red;
                    textBoxSeaPort.BackColor = m_booking.m_trip.m_seaPort.ToString() == m_booking.BookingHistory.m_trip.m_seaPort.ToString() ? Color.Cornsilk : Color.Red;
                    textBoxTrip.BackColor = m_booking.m_trip.ToString() == m_booking.BookingHistory.m_trip.ToString() ? Color.Cornsilk : Color.Red;
                    textBoxRemark.BackColor = m_booking.m_remark == m_booking.BookingHistory.m_remark ? Color.Cornsilk : Color.Red;
                    textBoxticketType.BackColor = m_booking.m_ticketType.ToString() == m_booking.BookingHistory.m_ticketType.ToString() ? Color.Cornsilk : Color.Red;
                    dateTimePickerBookDate.BackColor = m_booking.m_bookingDate == m_booking.BookingHistory.m_bookingDate ? Color.Cornsilk : Color.Red;
                    textBoxTravelAgent.BackColor = m_booking.m_travelAgent.Name == m_booking.BookingHistory.m_travelAgent.Name ? Color.Cornsilk : Color.Red;
                    dateTimePickerReturn.BackColor = m_booking.m_returnDate == m_booking.BookingHistory.m_returnDate ? Color.Cornsilk : Color.Red;
                   // dateTimePickerReturnTime.BackColor = m_booking.m_returntrip.m_departureTime == m_booking.BookingHistory.m_returntrip.m_departureTime ? Color.Cornsilk : Color.Red;
                    dateTimePickerDate.BackColor = m_booking.m_trip.m_departureDate == m_booking.BookingHistory.m_trip.m_departureDate ? Color.Cornsilk : Color.Red;
                    dateTimePickerDepTime.BackColor = m_booking.m_trip.m_departureTime == m_booking.BookingHistory.m_trip.m_departureTime ? Color.Cornsilk : Color.Red;
                }
            }

            textBoxName.Text = m_booking.m_groupName;
            textBoxUserCode.Text = m_booking.m_bookingCode;
            numericUpDownBooked.Value = m_booking.m_bookNumber;
            textBoxSeaPort.Text = m_booking.m_trip.m_seaPort.ToString();
            textBoxTrip.Text = m_booking.m_trip.ToString();
            textBoxRemark.Text = m_booking.m_remark;
            textBoxticketType.Text = m_booking.m_ticketType.ToString();
            dateTimePickerBookDate.Value = m_booking.m_bookingDate;
            textBoxTravelAgent.Text = m_booking.m_travelAgent.Name;
            dateTimePickerReturn.Value = m_booking.m_returnDate;
            dateTimePickerReturnTime.Value = m_booking.m_returnDate;
            dateTimePickerDate.Value = m_booking.m_trip.m_departureDate;
            dateTimePickerDepTime.Value = m_booking.m_departureDate;

            listViewPassenger.Items.Clear();
            foreach (Passenger p in m_booking.m_passengerList)
            {
                p.m_passport = m_passportService.GetPassportByID(p.m_passport.m_passportID);
                ListViewItem item = listViewPassenger.Items.Add(p.m_passport.m_passportNo);
                item.ForeColor = isSamePassenger(p)? Color.Black : Color.Red;
                item.SubItems.Add(p.m_passport.m_name);
                item.SubItems.Add(p.m_passport.m_gender);
                item.SubItems.Add(p.m_passport.m_birthDate.ToString("dd-MMM-yyyy"));
                item.SubItems.Add(p.m_passport.m_nationality);
                item.SubItems.Add(p.m_passport.m_issueDate.ToString("dd-MMM-yyyy"));
                item.SubItems.Add(p.m_ticketNo);
                item.SubItems.Add(p.m_passengerStatus.ToString());
                item.Checked = p.m_passengerStatus == PassengerStatus.Boarding;
                item.Tag = p;
            }
        }

        private bool isSamePassenger(Passenger m_passenger)
        {
            bool sameTicket = true;
            if (m_passenger.m_passengerStatus == PassengerStatus.ReCheckIn)
            {
                m_passenger.PassangerHistory = m_bookingService.GetPassengerHistoryByPassengerID(m_passenger.m_passangerID);
                if (m_passenger.PassangerHistory != null)
                    sameTicket = m_passenger.PassangerHistory.m_ticketNo == m_passenger.m_ticketNo;
            }
            return
                sameTicket &&
            m_passenger.m_passport.m_issueDate == m_passenger.m_issueDate &&
            m_passenger.m_passport.m_expireDate == m_passenger.m_expireDate &&
            m_passenger.m_passport.m_country == m_passenger.m_country &&
            m_passenger.m_passport.m_officeIssue == m_passenger.m_officeIssue &&
            m_passenger.m_passport.m_passportNo == m_passenger.m_passportNo &&
          m_passenger.m_passport.m_name == m_passenger.m_name &&
            m_passenger.m_passport.m_gender.ToString() == m_passenger.m_gender.ToString() &&
             m_passenger.m_passport.m_birthPlace == m_passenger.m_birthPlace &&
            m_passenger.m_passport.m_birthDate == m_passenger.m_birthDate &&
            m_passenger.m_passport.m_nationality == m_passenger.m_nationality &&
            m_passenger.m_passport.m_placeOfResidence == m_passenger.m_placeOfResidence &&
            m_passenger.m_passport.m_occupation == m_passenger.m_occupation &&
           m_passenger.m_passport.m_maritalStatus.ToString() == m_passenger.m_maritalStatus.ToString() &&
           m_passenger.m_passport.m_address == m_passenger.m_address &&
            m_passenger.m_passport.m_city == m_passenger.m_city &&
            m_passenger.m_passport.m_zipcode == m_passenger.m_zipcode &&
            m_passenger.m_passport.m_remark == m_passenger.m_remark &&
            m_passenger.m_passport.m_idnumber == m_passenger.m_idnumber;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            foreach (ListViewItem itm in listViewPassenger.Items)
            {
                itm.Checked = true;
            }
        }

        private void listViewPassenger_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewPassenger.SelectedItem != null)
            {
                buttonDatils.Enabled = listViewPassenger.SelectedItem != null;
            }
        }

        private void buttonDatils_Click(object sender, EventArgs e)
        {
            if (listViewPassenger.SelectedItem != null)
            {
                if (listViewPassenger.SelectedItem.Tag == null) return;
                Passenger p = (Passenger)listViewPassenger.SelectedItem.Tag;
                PassengerForm frm = new PassengerForm(this.Name, p, p.m_passport, m_current_user, m_mainForm, this, EditMode.Create);
                frm.ShowDialog();
            }
        }

        public void AddPassenger(Passenger p)
        {
            throw new NotImplementedException();
        }




        public bool isAlreadyExist(Passenger p)
        {
            throw new NotImplementedException();
        }


        public void UpdatePassenger(Passenger p)
        {
            throw new NotImplementedException();
        }
    }
}